<?php
/**
* @version		1.0: view.html.php marum56
* @package		Joomla
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.view');

/**
 * HTML View class for the Users component
 *
 * @static
 * @package		Joomla
 * @subpackage	Users
 * @since 1.0
 */
class UsersViewUsers extends JView
{
	function display($tpl = null)
	{
		global $mainframe, $option;

		$db		=& JFactory::getDBO();
		$currentUser	=& JFactory::getUser();
		$acl		=& JFactory::getACL();
		
		/*
		 * Zapis/odczyt stanu strony w obiekcie klasy JRegistry,
		 * który znajduje sie w tablicy sesji.
		 */
		// Filter na wybrana kolumne
		$filter_order		= $mainframe->getUserStateFromRequest( "$option.filter_order", 'filter_order', 'a.name', 'cmd' );
		// Filter na sposob sortowania: rosnacy lub malejacy
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option.filter_order_Dir", 'filter_order_Dir', '', 'word' );
		$filter_type		= $mainframe->getUserStateFromRequest( "$option.filter_type", 'filter_type', 0,	'string' );
		$filter_del		= $mainframe->getUserStateFromRequest( "$option.filter_del", 'filter_del', 0, 'int' );
		$search			= $mainframe->getUserStateFromRequest( "$option.search", 'search', '', 'string' );
		if (strpos($search, '"') !== false) {
			$search = str_replace(array('=', '<'), '', $search);
		}
		$search = JString::strtolower($search);

		// Limit ilosci wyswietlanych wierszy na stronie
		$limit	= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		// Limit poczatkowy tzn. od ktorego wiersza tabeli sql rozpoczynamy wyswietlanie na stronie
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		//*************************

		$where = array();
		if (isset( $search ) && $search!= '') {
			$searchEscaped = $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			$where[] = 'a.username LIKE '.$searchEscaped.' OR a.email LIKE '.$searchEscaped;
		}
		//Filtrowanie po grupie
		if ($filter_type) {
			$where[] = 'a.usertype = LOWER( '.$db->Quote($filter_type).' ) ';
		}
		//Filtrowanie zwolnionych
		if ( $filter_del == 0) {
			$where[] = 'a.del = 0';
		}
		else if ($filter_del == 1) {
			$where[] = 'a.del = 1';
		}

		// exclude any child group id's for this user
		$pgids = $acl->get_group_children( $currentUser->get('gid'), 'ARO', 'RECURSE' );

		if (is_array( $pgids ) && count( $pgids ) > 0) {
			JArrayHelper::toInteger($pgids);
			$where[] = 'a.gid NOT IN (' . implode( ',', $pgids ) . ')';
		}
/*		$filter = '';
		if ($filter_logged == 1 || $filter_logged == 2) {
			$filter = ' INNER JOIN #__session AS s ON s.userid = a.id';
		}
*/

		// Zapewnienie ze filter_order ma prawidlowa wartosc.
		if (!in_array($filter_order, array('a.username', 'a.block', 'groupname', 'a.email', 'a.lastvisitDate', 'a.id'))) {
			$filter_order = 'a.name';
		}
		// Zapewnienie ze filter_order_Dir ma prawidlowa wartosc.
		if (!in_array(strtoupper($filter_order_Dir), array('ASC', 'DESC'))) {
			$filter_order_Dir = '';
		}

		$orderby = ' ORDER BY '. $filter_order .' '. $filter_order_Dir;
		// Wyszukanie najmlodszego rekordu  
		$where[] = 'a.registerDate = (SELECT max(registerDate) 
		                              FROM #__users
		                              WHERE pesel = a.pesel)';		            
		$where = ( count( $where ) ? ' WHERE (' . implode( ') AND (', $where ) . ')' : '' );

		// Ile rekordow do wyswietlenia
		$query = 'SELECT COUNT(a.id)'
		. ' FROM #__users AS a'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pagination = new JPagination( $total, $limitstart, $limit );
		//*****************
		
		$query = 'SELECT a.*, g.name AS groupname'
			. ' FROM #__users AS a'
			. ' INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id'
			. ' INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.id'
			. ' INNER JOIN #__core_acl_aro_groups AS g ON g.id = gm.group_id'
			. $filter
			. $where
			. ' GROUP BY a.id'
			. $orderby
		;
		$db->setQuery( $query, $pagination->limitstart, $pagination->limit );
		$rows = $db->loadObjectList();

		// Utworzenie pola zalogowani tabeli html
		$n = count( $rows );
		$template = 'SELECT COUNT(s.userid)'
			. ' FROM #__session AS s'
			. ' WHERE s.userid = %d'
		;
		for ($i = 0; $i < $n; $i++)
		{
			$row = &$rows[$i];
			$query = sprintf($template, intval( $row->id ));
			$db->setQuery( $query );
			$row->loggedin = $db->loadResult();
		}

		// get list of Groups for dropdown filter
		$query = 'SELECT name AS value, name AS text'
			. ' FROM #__core_acl_aro_groups'
			. ' WHERE name != "ROOT"'
			. ' AND name != "USERS"'
			. ' AND name != "Public Backend"'
 		;
		
		//Usunięcie z kontrolki grupy pola "Administrator",
		// gdy "Zarzad" jest zalogowany
   	        if (strtolower($currentUser->usertype) == 'zarzad') {
   	        	$query .= 'AND name != "Administrator"';
   	        }
		
		
		$db->setQuery( $query );
		$types[] = JHTML::_('select.option',  '0', '- '. JText::_( 'Select Group' ) .' -' );
		$types[] = JHTML::_('select.option',  '', 'Wszystkie grupy' );
		foreach( $db->loadObjectList() as $obj )
		{
			$types[] = JHTML::_('select.option',  $obj->value, JText::_( $obj->text ) );
		}
		$lists['type'] 	= JHTML::_('select.genericlist',   $types, 'filter_type', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', "$filter_type" );

		// Lista selekt usunietych
		$lists['del'] = msSelect::Arch($filter_del, 'Aktualni pracownicy', 'Archiwalni');
		
		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search']= $search;

		$this->assignRef('user', JFactory::getUser());
		$this->assignRef('lists', $lists);
		$this->assignRef('items', $rows);
		$this->assignRef('pagination', $pagination);

		parent::display($tpl='pdf');
	}
}
